package com.cn.xt.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.Map.Entry;
/**
 * Feign消息配置类
 * @author liuyu on 2021/1/14.
 */
@Configuration
@EnableFeignClients
public class FeignLogConfig implements RequestInterceptor{

	@Override
	public void apply(RequestTemplate requestTemplate) {
		HttpServletRequest request = getHttpServletRequest();

	    if (Objects.isNull(request)) {
	      return;
	    }

	    Map<String, String> headers = getHeaders(request);
	    if (headers.size() > 0) {
	    	Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
	    	while (iterator.hasNext()) {
	    		Entry<String, String> entry = iterator.next();
	    		// 把请求过来的header请求头 原样设置到feign请求头中
	    		// 包括token
	    		requestTemplate.header(entry.getKey(), entry.getValue());
	    	}
	    }
	}
	
	private HttpServletRequest getHttpServletRequest() {
		try {
	      // 这种方式获取的HttpServletRequest是线程安全的
	      return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
	    } catch (Exception e) {
	      
	      return null;
	    }
	}

	private Map<String, String> getHeaders(HttpServletRequest request) {
	    
	    Map<String, String> map = new LinkedHashMap();
	  
	    Enumeration<String> enums = request.getHeaderNames();
	    while (enums.hasMoreElements()) {
	      String key = enums.nextElement();
	      String value = request.getHeader(key);
	      map.put(key, value);
	    }
	    
	    return map;
	}
	

	@Bean
	Logger.Level feignLoggerLevel() {
		return Logger.Level.FULL;
	}
}